<?php 
// define('INSTAGRAM_ACCESS_TOKEN', "*************************");
/*
 * Instagram Class, by Olivier St-Laurent
 * 
 * Must define INSTAGRAM_ACCESS_TOKEN in config.php
 * Usage : 
 *      $instagram = new Instagram();
 *      $instagram->getRecentPictures('USER', LIMIT);
 *      $recentPicturesArray = $instagram->getPictureList();
 */
class Instagram{
    public $accessToken = INSTAGRAM_ACCESS_TOKEN;
    
    public $userInfo = null;
    public $userID = null;
    public $response = null;
    public $json_response = null;
    public $pictureList = null;
    
    public function getUserID($userName){
        $ch = curl_init("https://api.instagram.com/v1/users/search?q=".$this->getNameFromUrl($userName)."&access_token=".$this->accessToken);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $json_response = json_decode($response);
        if ($json_response->data) {
            $this->userInfo = $json_response->data[0];
            $this->userID = $this->userInfo->id;
            curl_close($ch);
            return $this->userID;
        }
    }
    
    public function getRecentPictures($user,$count=null){
        if (is_int($user)) {
            $this->userID = $user;
        } else {
            $this->getUserID($user);
        }
        if ($this->userID) {
            $ch = curl_init("https://api.instagram.com/v1/users/".$this->userID."/media/recent?".($count? 'count='.$count.'&':'')."access_token=".$this->accessToken);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $this->response = curl_exec($ch);
            if ($this->response) {
                $this->json_response = json_decode($this->response);
                curl_close($ch);
                return $this->pictureList = $this->json_response;
            }
        }
    }
    
    public function getPictureList(){
        if ($this->pictureList === null) {
            return array();
        }
        $list = array();
        foreach($this->pictureList->data as $data){
            if ($data->type == 'image') {
                $list[] = $data->images->low_resolution->url;
            }
        }
        return $list;
    }
    
    public function getNameFromUrl($url){
        return preg_replace("#(^.*/)|(^)([a-z0-9_\.-]+)$#iu", "$3", $url);
    }
    
}
